package com.gjintel.business.enquire.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.gjintel.business.enquire.model.ProjectEnquire;
import com.gjintel.business.enquire.service.IProjectEnquireService;
import com.gjintel.business.proj.model.ProjectInfo;
import com.gjintel.framework.log.model.TSysWarningLog;
import com.gjintel.framework.register.model.RegisterUser;
import com.gjintel.framework.res.model.Resources;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.user.service.IUserService;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.framework.util.FileResUtil;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.dao.Sort;
import com.gjintel.sdk.util.DateJsonValueProcessor;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 *  项目询标函询问
 * @author wei
 *
 */
@Controller
@RequestMapping("/business/enquire")
public class ProjectEnquireController {
	
	@Resource
	private IProjectEnquireService enquireService;
	
	@Resource
	private IUserService userService;
	
	/**
	 * 投标人询标管理页面
	 * @param session
	 * @return
	 */
	@RequestMapping("/bidder/index")
	public ModelAndView index(HttpSession session) {
		ModelAndView mv = new ModelAndView("/enquire/bidder/enquire");
		return mv;
	}
	
	/**
	 * 询标界面
	 * @param session
	 * @return
	 */
	@RequestMapping("/chart")
	public ModelAndView chart(String projId,String senderId) {
		ModelAndView mv = new ModelAndView("/commons/js/chart/chart");
		ProjectInfo project = this.enquireService.get(ProjectInfo.class, projId);
		mv.addObject("projId", projId);
		mv.addObject("senderId", senderId);
		mv.addObject("project", project);
		return mv;
	}
	
	/**
	 * 投标人询标列表
	 * @param session
	 * @param page
	 * @param sort
	 * @param enquire
	 * @return
	 */
	@RequestMapping("/bidder/list")
	@ResponseBody
	public JSONObject list(HttpSession session,Page page,Sort sort,ProjectEnquire enquire){
		User user = (User) session.getAttribute("loginUser");
		if(user.getRegisterId()!=null){//为投标人
			enquire.setReceiverId(user.getRegisterId());
		}else{
			enquire.setReceiverId(user.getId());
		}
		List<ProjectEnquire> list=enquireService.findAll(page,sort,enquire);
		return CommUtil.getPageJSONData(page, true);
	}
	
	/**
	 * 投标人询标列表
	 * @param session
	 * @param page
	 * @param sort
	 * @param enquire
	 * @return
	 */
	@RequestMapping("/enquireList")
	@ResponseBody
	public String enquireList(HttpSession session,ProjectEnquire enquire){
		User user = (User) session.getAttribute("loginUser");
		if(user.getRegisterId()!=null){//为投标人
			enquire.setReceiverId(user.getRegisterId());
		}else{
			enquire.setReceiverId(user.getId());
		}
		List<ProjectEnquire> list=enquireService.findEnquireList(enquire);
		
		DateJsonValueProcessor dateProcessor = new DateJsonValueProcessor("yyyy-MM-dd");
		JsonConfig config = new JsonConfig();
		DateJsonValueProcessor processor = new DateJsonValueProcessor();
		config.registerJsonValueProcessor(Date.class, processor);
		config.registerJsonValueProcessor(java.sql.Date.class, dateProcessor);
		return JSONArray.fromObject(list, config).toString();
	}
	
	/**
	 * 添加
	 * @param request
	 * @param response
	 * @param enquire
	 * @return
	 * @throws Exception 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("/save")
	@ResponseBody
	public ProjectEnquire save(HttpSession session,HttpServletRequest request, HttpServletResponse response,ProjectEnquire enquire) throws IllegalStateException, Exception{
		response.setContentType("text/html;charset=utf-8");
		User user = (User) session.getAttribute("loginUser");
		//获取资源文件
		Resources res = this.enquireService.get(Resources.class, enquire.getResourceId());
		enquire.setCreateTime(new Date());
		
		//发送者
		if(user.getRegisterId()!=null){//为投标人
			enquire.setSenderId(user.getRegisterId());
			enquire.setSenderName(user.getLoginName());
		}else{
			enquire.setSenderId(user.getId());
			enquire.setSenderName(user.getLoginName());
		}
	
		//接受者
		RegisterUser register = this.enquireService.get(RegisterUser.class, enquire.getReceiverId());
		if(register!=null){//为投标人
			enquire.setReceiverId(register.getId());
			enquire.setReceiverName(register.getLoginName());
		}else{
			User receiver = this.enquireService.get(User.class, enquire.getReceiverId());
			if(receiver!=null){
				enquire.setReceiverName(receiver.getLoginName());
				enquire.setReceiverId(receiver.getId());
			}
		}
		
		if(res!=null){
			enquire.setResourceId(res.getId());
			enquire.setResourceName(res.getOldName());
		}
		this.enquireService.save(enquire);
		
		//发送消息提醒
		TSysWarningLog message = new TSysWarningLog();
		message.setTitle("系统信息");
		message.setContents("你有一条询标信息，请查看!");
		message.setCreateTime(new Date());
		message.setReaderId(enquire.getReceiverId());
		message.setReaderName(enquire.getReceiverName());
		this.enquireService.save(message);
		response.getWriter().write("{\"data\":\"ok\"}");
		return null;
	}

	/**
	 * 保存资源文件
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@Deprecated
	public Resources saveResource(HttpServletRequest request, HttpServletResponse response) throws IOException {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 取得request中的文件,获取一个list集合
		MultipartFile file = multipartRequest.getFile("Filedata");
		// 得到文件的相对路径
		String relativePath = File.separator + "project";
		String uploadPath = request.getSession().getServletContext().getRealPath("file_resource") + relativePath;
		File filePath = new File(uploadPath);
		// 判断文件夹是否存在，如果不存在给与创建出来
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		String fileName = file.getOriginalFilename();
		Resources res = new Resources();
		String exeName=System.currentTimeMillis()+"";
		if(fileName!=null){
			exeName = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		}
		res.setExeName(exeName);
		res.setFilePath(relativePath);
		res.setFileSize(file.getSize());
		res.setOldName(fileName);
		Resources resource = FileResUtil.addFileRes(res); // 保存文件记录
		File newFile = new File(uploadPath, res.getId() + res.getExeName());
		file.transferTo(newFile);
		return resource;
	}
	
	
	
}
